package supplier

import (
	"context"
	"fmt"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SupplierListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSupplierListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SupplierListLogic {
	return &SupplierListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SupplierListLogic) SupplierList(req *types.SupplierListRequest) (resp *types.SupplierListResponse, err error) {
	resp = new(types.SupplierListResponse)

	//1.查询分页
	var query string
	if len(req.Keywords) > 0 {
		query += fmt.Sprintf(` where name like '%%%s%%'`, req.Keywords)
	}
	queryWithLimit := query + fmt.Sprintf(" order by id desc limit %d,%d", (req.Page-1)*req.Size, req.Size)
	clients, err := l.svcCtx.SupplierModel.FindByPage(l.ctx, queryWithLimit)
	if err != nil {
		if err == model.ErrNotFound {
			resp.Code = http.StatusNoContent
			resp.Msg = "没有数据"
			return
		}

		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return
	}

	//2.计算总数
	total, err := l.svcCtx.SupplierModel.Count(l.ctx, query)
	if err != nil {
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return
	}

	resp.Data.Total = total
	for _, client := range clients {
		resp.Data.List = append(resp.Data.List, types.Supplier{
			Id:        client.Id,
			Name:      client.Name,
			CreatedAt: client.CreatedAt.Unix(),
		})
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return
}
